package com.mycinema.web.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.mycinema.biz.CategoryBiz;
import com.mycinema.biz.MovieBiz;
import com.mycinema.entity.Category;
import com.mycinema.entity.Movie;

@Controller
@RequestMapping("/admin")
public class AdminHomeController {

	@Autowired
	private CategoryBiz categoryBiz;

	@Autowired
	private MovieBiz movieBiz;

	@RequestMapping("/edit")
	public String edit(Model model, int id) {
		Movie movie = movieBiz.getById(id);
		List<Category> categories = categoryBiz.getAll();
		model.addAttribute("movie", movie);
		model.addAttribute("categories", categories);
		return "movie-edit"; // 页面名字
	}

	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public String save(Model model, @Valid Movie movie,//该对象要被验证
			BindingResult result,
			MultipartFile movieImage,
			HttpServletRequest request ) {// 要和上传name一样

		if (!movieImage.isEmpty()) {
			// 获取MovieImage的物理路径
			String path = request.getServletContext()
					.getRealPath("MovieImages");// 获取文件名 创建一个文件
			String filename = path + "/" + movie.getMovieCode() + ".jpg";
			System.out.println(filename);
			try {
				FileOutputStream fileOutputStream = new FileOutputStream(
						filename);
				// 写入文件
				fileOutputStream.write(movieImage.getBytes());
				// 关闭文件
				fileOutputStream.close();
				System.out.println("上传成功!");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if (result.hasErrors())
		{
			result.addError(new ObjectError("movie","movie验证不通过"));
			model.addAttribute("categoryies",categoryBiz.getAll());
			model.addAttribute("movie",movie);
			return "movie-edit";
		}else {
			movieBiz.updateMovie(movie);
			return "redirect:/list";	
		}
	}

	// //局部(只能在当前controller使用)的日期类型转换器
	// @InitBinder //参数绑定之前调用 Date一定是util 不能用于sql
	// public void initBind(WebDataBinder binder){
	// SimpleDateFormat sdf =new SimpleDateFormat("yyyy-mm-dd");
	// //SimpleDateFormat sdf2 =new SimpleDateFormat("yyyy/mm/dd");
	//
	// //sdf2.setLenient(true);
	// sdf.setLenient(true);
	// //注册日期转换器
	// binder.registerCustomEditor(Date.class,new CustomDateEditor(sdf, true));
	// // binder.registerCustomEditor(Date.class,new CustomDateEditor(sdf2,
	// true));
	// }

	@RequestMapping("/upload")
	public String upload() {
		return "upload";
	}

	// 多文件上传
	@RequestMapping("/uploadFile")
	public String uploadFiles(
			@RequestParam(required = false, value = "files") MultipartFile[] files,
			HttpServletRequest request) {
		String path = request.getServletContext().getRealPath("files");
		for (MultipartFile multipartFile : files) {
			String filename = path + "/" + multipartFile.getOriginalFilename();
			File file = new File(filename);
			try {
				multipartFile.transferTo(file);
				System.out.println(filename);
			} catch (IllegalStateException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
		return "upload";
	}

	//下载文件
	@RequestMapping(value = "downLoad")
	public void downLoad(String fileName, HttpServletResponse response,
			HttpServletRequest request) {
		response.setCharacterEncoding("utf-8");
		response.setContentType("multipart/form-data");
		response.setHeader("content-disposition", "attachement;filename="
				+ fileName);
		try {
			// 获取文件的物理路径
			String path = request.getSession().getServletContext()
					.getRealPath("/MovieImages/" + fileName);
			System.out.println(path);
			File file = new File(path);
			FileInputStream inputStream = new FileInputStream(file);
			OutputStream os = response.getOutputStream();
			byte[] b = new byte[1024];
			int length;
			while ((length = inputStream.read(b)) > 0) {
				os.write(b, 0, length);
			}
			inputStream.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	

}
